package com.hdcx.Minfresh.adapter;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hdcx.Minfresh.R;
import com.hdcx.Minfresh.activity.AddAddressActivity;
import com.hdcx.Minfresh.bean.AdressWrapper;
import com.hdcx.Minfresh.bean.CartWrapper;
import com.hdcx.Minfresh.bean.GoodListWrapper;
import com.hdcx.Minfresh.bean.UserInfoBean;
import com.hdcx.Minfresh.fragment.ShoppingCartFragment;
import com.hdcx.Minfresh.model.ShoppingCar;
import com.hdcx.Minfresh.model.Statue;
import com.hdcx.Minfresh.url.MyUrl;
import com.hdcx.Minfresh.util.AppUtil;
import com.hdcx.Minfresh.util.GsonUtils;
import com.hdcx.Minfresh.util.ShpfUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/11/9.
 */

public class ShoppingCartAdapter extends RecyclerView.Adapter<ShoppingCartAdapter.Holder> {
    FragmentActivity mActivity;
    ShoppingCartFragment fragment;
    //List<Boolean> isSelect_booleans = new ArrayList<>();
    GoodListWrapper data;
    private CartWrapper ShareData;
    Boolean tag;//是否能进去去结算
    ShoppingCar shoppingCar;

    public ShoppingCartAdapter(FragmentActivity mActivity, ShoppingCartFragment shoppingCartFragment) {
        this.mActivity = mActivity;
        fragment = shoppingCartFragment;
    }

    @Override
    public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(mActivity);
        View view = layoutInflater.inflate(R.layout.item_fragment_cart_, parent, false);
        return new Holder(view);
    }

    @Override
    public void onBindViewHolder(final Holder holder, final int position) {
        final GoodListWrapper.ListBean temp = data.getList().get(position);
        AppUtil.showPic(data.getList().get(position).getPic(), holder.img_main);
        holder.tv_name.setText(temp.getTitle());
        holder.tv_intro.setText(temp.getShort_title());
        holder.tv_intro_2.setText("规格:" + temp.getEtalon() + temp.getUnits());
        String tempString = "￥" + data.getList().get(position).getPrice() + "/" + data.getList().get(position).getUnits();
        SpannableString styledText = new SpannableString(tempString);
        styledText.setSpan(new TextAppearanceSpan(mActivity, R.style.tv_red), 0, tempString.length() - 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(mActivity, R.style.tv_size_25), 1, data.getList().get(position).getPrice().length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(mActivity, R.style.tv_size_13), tempString.length() - 2, tempString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        holder.tv_money.setText(styledText, TextView.BufferType.SPANNABLE);
        // holder.tv_money.setText("￥:" + temp.getPrice() + "/" + temp.getUnits());
        int realy_num = ShareData.getNumById(temp.getId()) > temp.getQuantity() ? temp.getQuantity() : ShareData.getNumById(temp.getId());
        holder.tv_num.setText("" + realy_num);
        temp.setRealy_quantity(realy_num);

        holder.img_select.setImageResource(temp.getIs_select() ? R.drawable.ic_gou : R.drawable.ic_quan);
        holder.layout_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Boolean temp_select = temp.getIs_select();
                temp.setIs_select(!temp_select);
                notifyDataSetChanged();
            }
        });
        setTotle(holder, position);
        holder.img_jia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int timer_goods = shoppingCar.getList().get(position).getTimer_goods();
                Log.e("ShoppingCartAdapter", "ShoppingCartAdapter--onClick--" + timer_goods);
                if (timer_goods > 0) {
                    Toast.makeText(mActivity, "该商品为特价商品，每人仅限购1件", Toast.LENGTH_SHORT).show();
                    return;
                }
                int tempint = Integer.valueOf(holder.tv_num.getText().toString());
                tempint = tempint + 1 > temp.getQuantity() ? temp.getQuantity() : tempint + 1;
                temp.setRealy_quantity(tempint);
                ShareData.setNumById(temp.getId(), tempint);
                holder.tv_num.setText(tempint + "");
                notifyDataSetChanged();
            }
        });
        holder.img_jian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int tempint = Integer.valueOf(holder.tv_num.getText().toString());
                tempint = tempint - 1 > 0 ? tempint - 1 : 1;
                temp.setRealy_quantity(tempint);
                ShareData.setNumById(temp.getId(), tempint);
                holder.tv_num.setText(tempint + "");
                notifyDataSetChanged();
            }
        });
        setTotleMoney();
        fragment.bt_go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UserInfoBean user = ShpfUtil.getObject(ShpfUtil.LOGIN);
                JSONObject json = new JSONObject();
                try {
                    json.put("uid", user.getUserinfo().getId());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                OkHttpUtils.postString()
                        .url(MyUrl.ADDRESS)
                        .content(json.toString())
                        .build()
                        .execute(new Callback<AdressWrapper>() {
                            @Override
                            public AdressWrapper parseNetworkResponse(Response response) throws IOException {
                                String json = response.body().string();
                                return new Gson().fromJson(json, AdressWrapper.class);
                            }

                            @Override
                            public void onError(Call call, Exception e) {
                            }

                            @Override
                            public void onResponse(AdressWrapper response) {
                                if (response.getStatus() == 1) {
                                    if (tag) {
                      /*  Intent intent =new Intent(fragment.getActivity(), OrderUploadActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("cart", data);
                        intent.putExtras(bundle);*/
                                        JSONObject json = new JSONObject();
                                        AppUtil.showLoading(mActivity);
                                        OkHttpUtils.postString()
                                                .url(MyUrl.ISSHOPING)
                                                .content(json.toString())
                                                .build()
                                                .execute(new Callback<String>() {
                                                    @Override
                                                    public String parseNetworkResponse(Response response) throws IOException {
                                                        String json = response.body().string();
                                                        return json;
                                                    }

                                                    @Override
                                                    public void onError(Call call, Exception e) {
                                                        AppUtil.closeLoading();
                                                    }

                                                    @Override
                                                    public void onResponse(String response) {
                                                        AppUtil.closeLoading();
                                                        Statue statue = GsonUtils.parseJSON(response, Statue.class);
                                                        int status = statue.getStatus();
                                                        if (status == 1) {
                                                            fragment.onMyItemClick(data);
                                                        } else {
                                                            new AlertDialog.Builder(mActivity)
                                                                    .setMessage(statue.getInfo())
                                                                    .setPositiveButton("是", null)
                                                                    .create()
                                                                    .show();
                                                        }
                                                    }
                                                });
                                    }
                                } else {
                                    new AlertDialog.Builder(mActivity)
                                            .setTitle("提示")
                                            .setMessage("请添加收货地址")
                                            .setPositiveButton("是", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialogInterface, int i) {
                                                    Intent intent = new Intent(mActivity, AddAddressActivity.class);
                                                    mActivity.startActivity(intent);
                                                }
                                            })
                                            .setNegativeButton("否", null)
                                            .create()
                                            .show();
                                }
                            }
                        });
            }
        });
        fragment.right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final android.app.AlertDialog.Builder alterDialog = new android.app.AlertDialog.Builder(mActivity);
                alterDialog.setMessage("确定删除？");
                alterDialog.setCancelable(true);
                alterDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        for (int i = 0; i < data.getList().size(); i++) {
                            if (data.getList().get(i).getIs_select()) {
                                ShareData.deleteBy(data.getList().get(i).getId());
                                data.getList().remove(i);
                                i--;
                                setTotleMoney();
                                notifyDataSetChanged();
                            }
                        }

                        ShpfUtil.setObject(AppUtil.getUserId(), ShareData);
                        AppUtil.setMain_Cart();
                        //fragment.onMyItemClick();
                    }
                });
                alterDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                alterDialog.show();
            }
        });

    }


    private void setTotle(Holder holder, int position) {
        for (int i = 0; i < data.getList().size(); i++) {
            if (!data.getList().get(i).getIs_select()) {
                fragment.img_totle.setImageResource(R.drawable.ic_quan);
                return;
            }
        }
        fragment.img_totle.setImageResource(R.drawable.ic_gou);
    }

    @Override
    public int getItemCount() {
        if (data == null) {
            return 0;
        }
        return data.getList().size();
    }

    public void changeSelectAll(Boolean select_all) {
        for (int i = 0; i < data.getList().size(); i++) {
            data.getList().get(i).setIs_select(select_all);
        }
        notifyDataSetChanged();
    }

    public void setSharepData(CartWrapper cartData) {
        ShareData = cartData;
    }

    public void removeAndNoti() {
        data = null;
        notifyDataSetChanged();
    }


    public class Holder extends RecyclerView.ViewHolder {
        View view_last;
        ImageView img_select, img_jia, img_jian, img_main;
        LinearLayout layout_all;
        TextView tv_num, tv_name, tv_intro, tv_intro_2, tv_money;
        RelativeLayout layout_select;

        public Holder(View itemView) {
            super(itemView);
            view_last = itemView.findViewById(R.id.view_last);
            img_select = (ImageView) itemView.findViewById(R.id.img_select);
            img_jia = (ImageView) itemView.findViewById(R.id.img_jia);
            img_jian = (ImageView) itemView.findViewById(R.id.img_jian);
            img_main = (ImageView) itemView.findViewById(R.id.img_main);
            tv_num = (TextView) itemView.findViewById(R.id.tv_num);
            tv_name = (TextView) itemView.findViewById(R.id.tv_name);
            tv_intro = (TextView) itemView.findViewById(R.id.tv_intro);
            tv_intro_2 = (TextView) itemView.findViewById(R.id.tv_intro_2);
            tv_money = (TextView) itemView.findViewById(R.id.tv_money);
            layout_all = (LinearLayout) itemView.findViewById(R.id.layout_all);
            layout_select = (RelativeLayout) itemView.findViewById(R.id.layout_select);
        }
    }

    public void setData(GoodListWrapper cartData, ShoppingCar shoppingCar) {
        data = cartData;
        this.shoppingCar = shoppingCar;
        if (data != null && data.getList() != null) {
            for (int i = 0; i < data.getList().size(); i++) {
                data.getList().get(i).setIs_select(true);
            }
        }
        notifyDataSetChanged();
    }

    public void setTotleMoney() {
        float temp = 0;
        int cart_num = 0;
        for (int i = 0; i < data.getList().size(); i++) {
            cart_num = cart_num + data.getList().get(i).getRealy_quantity();
            if (data.getList().get(i).getIs_select()) {
                temp = temp + (data.getList().get(i).getRealy_quantity() * Float.valueOf(data.getList().get(i).getPrice()));
            }
        }
        tag = temp == 0 ? false : true;
        data.setTotle_money(temp);
        DecimalFormat df = new DecimalFormat("#####0.00 ");
        fragment.tv_totle_money.setText("共计：￥" + df.format(temp) + "元");
        AppUtil.setMain_Cart(cart_num);
    }

}
